﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace MyTRCP.Common.Services
{
    public class MyAudioRouteService : BackgroundService
    {
        private readonly ILogger<RemoteAudioRouteService> _logger;
        private readonly BlockingQueue<byte[]> _inQueue;
        private readonly List<BlockingQueue<byte[]>> _outQueueList;
        public MyAudioRouteService(ILogger<RemoteAudioRouteService> il, AudioConvertService iacs, AudioRecordService iars)
        {
            il.LogDebug($"MyAudioRouteService creating...");
            _logger = il;
            _inQueue = iacs.MyAudioRxQueue;
            _outQueueList = [iars.PcmQueue];
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation($"音频路由线程开始");
            await Task.Run(() =>
            {
                try
                {
                    while (!stoppingToken.IsCancellationRequested)
                    {
                        try
                        {
                            byte[] data = _inQueue.Take();
                            foreach (BlockingQueue<byte[]> outQ in _outQueueList)
                            {
                                outQ.Add(data);
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            _logger.LogInformation("音频路由线程循环接收到OperationCanceledException,跳出.");
                            break;
                        }
                        catch (Exception e)
                        {
                            _logger.LogError(e, $"音频路由线程循环内出现异常：{e.Message}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"音频路由线程出现异常：{ex.Message}");
                }
            }, stoppingToken);
            _logger.LogInformation($"音频路由线程结束");
        }
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogDebug("startasync called");
            return base.StartAsync(cancellationToken);
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            _inQueue.CancelTake();
            return base.StopAsync(cancellationToken);
        }
    }
}
